import psycopg2


class PSQLDB:

    DATABASE: str = 'Study'
    USER: str = 'postgres'
    PASSWORD: str = 'studyUser123'
    HOST: str = '192.168.86.148'

    def connection(self):
        try:
            conn = psycopg2.connect(dbname=self.DATABASE,
                                    user=self.USER,
                                    password=self.PASSWORD,
                                    host=self.HOST
                                    )
            return conn
        except psycopg2.OperationalError as er:
            print(er)
            return False

    def create_tables(self, sql: str):
        con = self.connection()
        cur = con.cursor()
        try:
            cur.execute(sql)
            con.commit()
            con.close()
            return 0
        except Exception as er:
            return er

    def insert(self, connect, sql: str):
        cur = connect.cursor()
        try:
            cur.execute(sql)
            connect.commit()
            cur.close()
            return 0
        except Exception as er:
            cur.close()
            connect.rollback()
            return er

    def exit_db(self, connect):
        connect.close()

    def select_db(self, sql: str) -> list:
        con = self.connection()
        cur = con.cursor()
        cur.execute(sql)
        data = cur.fetchall()
        con.rollback()
        con.close()
        return data
